// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    courses: [
      { id: 1, title: "Python基础入门课程", cover: "/pages/images/icon/python.png", videoUrl: "https://www.bilibili.com/video/BV1qW4y1a7fU" },
      { id: 2, title: "《高等数学》同济版 |宋浩老师", cover: "/pages/images/icon/高数.png", videoUrl: "https://www.bilibili.com/video/BV1Eb411u7Fw" },
      { id: 3, title: "黑马程序员Java零基础视频教程", cover: "/pages/images/icon/java.png", videoUrl: "https://www.bilibili.com/video/BV17F411T7Ao" },
      { id: 4, title: "《数据结构》| C语言版", cover: "/pages/images/icon/数据结构.png", videoUrl: "https://www.bilibili.com/video/BV1tNpbekEht" }
    ],
    words: [
      { word: "apple", meaning: "n. 苹果；苹果树" },
      { word: "banana", meaning: "n. 香蕉" },
      { word: "cherry", meaning: "n. 樱桃" }
    ],
    exams: [
      { name: "高考", date: "2025-06-07" },
      { name: "中考", date: "2025-06-14" },
      { name: "四六级", date: "2025-12-16" }
    ],
    isFlipped: false,
    autoSwitchTimer: null,
    currentContent: {}, // 统一内容存储
    lastUpdateType: 'word' // 记录上次更新类型
  },
 
  // 初始化内容
  initContent: function() {
    this.updateWordContent();
    this.scheduleExamUpdate();
  },
  // 更新单词内容
  updateWordContent: function() {
    const word = this.data.words[Math.floor(Math.random() * this.data.words.length)];
    this.setData({
      currentContent: {
        type: 'word',
        word: word.word,
        meaning: word.meaning,
        showHint: true
      },
      lastUpdateType: 'word'
    });
  },
  // 更新考试内容
  updateExamContent: function() {
    const exam = this.data.exams[Math.floor(Math.random() * this.data.exams.length)];
    const remaining = this.calculateRemainingTime(exam.date);
    
    this.setData({
      currentContent: {
        type: 'exam',
        name: exam.name,
        date: exam.date,
        remainingDays: remaining.days,
        remainingHours: remaining.hours,
        showHint: true
      },
      lastUpdateType: 'exam'
    });
  },
  // 点击卡片处理
  handleCardClick: function() {
    if (this.data.autoSwitchTimer) {
      clearTimeout(this.data.autoSwitchTimer);
      this.setData({ autoSwitchTimer: null });
    }

    const newState = !this.data.isFlipped;
    this.setData({ 
      isFlipped: newState,
      'currentContent.showHint': false 
    }, () => {
      if (!newState) { // 回到正面时重置自动切换
        this.startAutoSwitch(5000);
      }
    });
  },
  // 自动切换优化版
  startAutoSwitch: function(delay = 5000) {
    this.clearAutoSwitch();
    const timer = setTimeout(() => {
      this.setData({ isFlipped: !this.data.isFlipped }, () => {
        if (this.data.isFlipped) {
          this.updateExamContent();
        } else {
          this.updateWordContent();
        }
        this.startAutoSwitch();
      });
    }, delay);
    this.setData({ autoSwitchTimer: timer });
  },
  // 计算剩余时间
  calculateRemainingTime: function(examDate) {
    const now = new Date();
    const target = new Date(examDate);
    const diff = target - now;
    
    return {
      days: Math.max(Math.floor(diff / 86400000), 0),
      hours: Math.max(Math.floor((diff % 86400000) / 3600000), 0)
    };
  },

  // 定时更新考试数据（每分钟）
  scheduleExamUpdate: function() {
    setInterval(() => {
      if (this.data.lastUpdateType === 'exam') {
        this.updateExamContent();
      }
    }, 60000);
  },
  clearAutoSwitch: function() {
    if (this.data.autoSwitchTimer) {
      clearTimeout(this.data.autoSwitchTimer);
      this.setData({ autoSwitchTimer: null });
    }
  },

  onSearchHistoryTap: function (e) {
    const keyword = e.currentTarget.dataset.keyword;
    // 执行搜索逻辑，例如跳转到搜索结果页面
    console.log("点击搜索历史：", keyword);
  },

  onCheckIn() {
    wx.navigateTo({
      url: '/pages/home/check/check',
    });
  },

  onFreeMaterials: function () {
    // 学习成就逻辑
    console.log("点击学习成就");
    wx.navigateTo({
      url: '/pages/home/achieve/achieve',
    });
  },

  onMyPlan: function () {
    // 我的计划逻辑
    console.log("点击我的计划");
    wx.navigateTo({
      url: '/pages/home/plane/plane',
    });
  },

  onMyFocus: function () {
    // 开始专注逻辑
    console.log("点击开始专注");
    wx.navigateTo({
      url: '/pages/home/focus/focus'
    });
  },

  // 跳转至独立播放页
  navigateToCourse(e) {
    const { id, url, title } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/home/course/player?id=${id}&url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('onLoad');
    this.startAutoSwitch(); // 页面加载时启动自动切换
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopAutoSwitch(); // 页面卸载时停止自动切换
  }
});